- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathFirstNegativeNumInEverySubarray.java
50 lines (40 loc) Β· 889 Bytes
/
FirstNegativeNumInEverySubarray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
packagesection11_Queue;
importjava.util.LinkedList;
importjava.util.Queue;
publicclassFirstNegativeNumInEverySubarray {
publicstaticvoidmain(String[] args) {
int[] arr = { 12, -1, -7, 8, -15, 30, 16, 28 };
intwindowSize = 3;
firstNegativeInSubarray(arr, windowSize);
}
staticvoidfirstNegativeInSubarray(int[] arr, intk) {
Queue<Integer> q = newLinkedList<Integer>();
inti;
for (i = 0; i < k; i++) {
if (arr[i] < 0) {
q.add(i);
}
}
for (; i < arr.length; i++) {
if (!q.isEmpty()) {
System.out.print(arr[q.peek()] + " ");
} else {
System.out.print(0 + " ");
}
while (!q.isEmpty() && q.peek() <= i - k) {
q.remove();
}
if (arr[i] < 0) {
q.add(i);
}
}
if (!q.isEmpty()) {
System.out.print(arr[q.peek()] + " ");
} else {
System.out.print(0 + " ");
}
}
}
/* output:
-1 -1 -7 -15 -15 0
*/